package cn.net.shuxing.yifu.common.back.controller;

import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.service.OssCommonService;
import cn.net.shuxing.yifu.common.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

@RestController
public class WangEditorController {

    @Autowired
    private OssCommonService ossCommonService;

    private String bucketName = OssConstant.ossBucketName;

    @RequestMapping("/back/wang/upload")
    public Object upload(MultipartHttpServletRequest request) throws IOException {
        Map<String,Object> resultMap = new HashMap<>();
        Map<String, MultipartFile> fileMap = request.getFileMap();
        Set<String> keySet = fileMap.keySet();
        resultMap.put("errno",0);
        List<Map<String,String>> imgUrls = new ArrayList<>();
        for (String filename : keySet)
        {
            MultipartFile multipartFile = fileMap.get(filename);
            InputStream inputStream = multipartFile.getInputStream();
            int size = (int) multipartFile.getSize();
            byte[] img = new byte[size];
            inputStream.read(img);
            inputStream.close();
            String suffix = FileUtil.getFileExtName(filename);
            filename  = LocalDateTime.now().toString() + filename;
            ossCommonService.uploadFile(bucketName,filename,img,suffix);
            Map<String,String> map = new HashMap<>();
            map.put("url",ossCommonService.getUrl(bucketName,filename));
            map.put("objectName",filename);
            imgUrls.add(map);
        }
        resultMap.put("data",imgUrls);
        return resultMap;
    }
}
